package controller;

import com.scorpio.utils.StringUtils;
import dao.D1;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

@WebServlet(urlPatterns = "/login")
public class LoginController extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html");

        HttpSession session = request.getSession();

        if (session.getAttribute("username") != null && session.getAttribute("username").equals("admin")) {

            System.out.println("已经登录，直接跳到成功页面!");
            response.sendRedirect("success.jsp");
            return;
        }

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (username.equals("admin") && password.equals("123456")) {
            System.out.println("登录成功");
            String autoLogin = request.getParameter("autoLogin");
            System.out.println("autoLogin:" + autoLogin);
            String usernameCode = URLEncoder.encode(username, "UTF-8");
            Cookie usernameCookie = new Cookie("username", usernameCode);
            Cookie passwordCookie = new Cookie("password", password);
            Cookie autoLoginCookie = new Cookie("autoLogin", autoLogin);
            if (autoLogin != null) {
                //设置持久化时间
                autoLoginCookie.setMaxAge(60);
                usernameCookie.setMaxAge(60);
                passwordCookie.setMaxAge(10 * 60);
                //设置cookie携带路径
                usernameCookie.setPath(request.getContextPath());
                passwordCookie.setPath(request.getContextPath());
                //发送cookie
                response.addCookie(usernameCookie);
                response.addCookie(passwordCookie);
                response.addCookie(autoLoginCookie);
            } else {
                autoLoginCookie.setMaxAge(0);
                response.addCookie(autoLoginCookie);
            }
            session.setAttribute("username", username);
            session.setAttribute("password", password);
            //设置session超时时间
            session.setMaxInactiveInterval(60);
            response.sendRedirect("success.jsp");
        } else {
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

}